﻿using SharpDX;
using TriangleNet.Data;

namespace RPGOnlineWPF.Extensions
{
	public static class MeshExtension
	{
		public static bool IsMouseOver(this TriangleNet.Mesh mesh, Vector2 mousePosition)
		{
			foreach (var triangle in mesh.Triangles)
			{
				var v1 = triangle.GetVertex(0);
				var v2 = triangle.GetVertex(1);
				var v3 = triangle.GetVertex(2);

				if (IsPointInTri(mousePosition, v1, v2, v3))
					return true;
			}

			return false;
		}

		private static double Sign(Vector2 p1, Vertex p2, Vertex p3)
		{
			return (p1.X - p3.X) * (p2.Y - p3.Y) - (p2.X - p3.X) * (p1.Y - p3.Y);
		}

		private static bool IsPointInTri(Vector2 pt, Vertex v1, Vertex v2, Vertex v3)
		{
			bool b1, b2, b3;

			b1 = Sign(pt, v1, v2) < 0.0f;
			b2 = Sign(pt, v2, v3) < 0.0f;
			b3 = Sign(pt, v3, v1) < 0.0f;

			return ((b1 == b2) && (b2 == b3));
		}
	}
}